<template>
  <el-dialog width="500px" @close="handleClose" @open="handleOpen">

    <el-form ref="form" :model="form" :rules="rules"  @submit.prevent>
      <el-form-item :label="$t('system.ram.app_name')" prop="name">
        <el-input v-model="form.name" maxlength="32" show-word-limit :placeholder="$t('system.ram.enter_app_name')" @blur="() => form.name = form.name.trim()" />
      </el-form-item>
    </el-form>
    <template #footer>

      <span class="dialog-footer">
        <el-button  @click="handleClose">{{ $t('common.cancel') }}</el-button>
        <el-button  type="primary" :loading="confirmLoading" @click="handleConfirm">
          {{ $t('common.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>

import { addUser } from '@/api/user'

export default {
  props: {
    visible: Boolean // previously was `value: String`
  },
  emits: ['update:model-value', 'submit', 'postey'],
  data() {
    return {
      confirmLoading: false,
      form: {
        platCode: ['RAM'],
        orgId: '',
        userType: 2,
        countryCode: '',
        name: ''
      },
      orgId: '',
      countryCode: '',
      rules: {
        name: [
          {
            required: true,
            message: this.$t('system.ram.validate_require'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    handleOpen() {
      const userInfo = JSON.parse(
        localStorage.getItem(this.$store.getters.keys.storage.username)
      )
      this.orgId = String(userInfo.orgId)
      this.countryCode = userInfo.countryCode ? String(userInfo.countryCode) : null
      this.confirmLoading = false
    },
    handleConfirm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          console.log(this.countryCode)
          this.confirmLoading = true
          this.form.orgId = this.orgId
          this.form.countryCode = this.countryCode
          addUser(this.form).then((res) => {
            this.confirmLoading = false
            this.$message.success(
              this.$t('system.ram.add_success')
            )
            this.$emit('submit')
            const ram = {}
            ram.ramId = res.username
            ram.ramKey = res.password
            ram.userId = res.userId
            this.$emit('postKey', ram)
            this.handleClose()
          }).catch((e) => {
            this.confirmLoading = false
            this.$confirmError(e)
          })
        }
      })
    },
    handleClose() {
      console.log('cancel');
      
      this.confirmLoading = false
      this.$refs['form'].resetFields()
      this.$emit('update:model-value', false)
    }
  }
}
</script>

<style>
</style>
